package com.lpj.base.id.generator.autoconfigure;

import com.lpj.base.id.generator.service.impl.IdServiceImpl;
import com.lpj.base.id.generator.service.impl.provider.MachineIdProvider;
import com.robert.vesta.service.intf.IdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

/**
 * @author LiPengJu
 * @date: 2020/4/19
 */
@ConfigurationProperties(prefix = "service.id")
public class IdGeneratorProperties implements InitializingBean {
    private Logger logger = LoggerFactory.getLogger(IdGeneratorProperties.class);

    /**
     * id类型
     * 0 最大峰值型
     * 1 最小粒度型
     */
    private Long type;

    /**
     * 版本号 0 或 1
     */
    private Long version;

    private String machineIdKey;

    private String machineIdProvider;

    private List<Long> machineIds;

    public void afterPropertiesSet() throws Exception {
        if (this.type == null) {
            logger.info("No ID type is configured, use the default type: 1");
            this.type = 1L;
        }
        if (this.version == null) {
            logger.info("The version number of ID generator is not configured. The default version number is used : 0");
            this.version = 0L;
        }
        if (this.machineIdProvider == null) {
            logger.info("No machineIdProvider is configured, use the default provider: 'on class'");
        }
    }

    public String getMachineIdKey() {
        return machineIdKey;
    }

    public void setMachineIdKey(String machineIdKey) {
        this.machineIdKey = machineIdKey;
    }

    public Long getType() {
        return type;
    }

    public void setType(Long type) {
        this.type = type;
    }

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public List<Long> getMachineIds() {
        return machineIds;
    }

    public void setMachineIds(List<Long> machineIds) {
        this.machineIds = machineIds;
    }

    public String getMachineIdProvider() {
        return machineIdProvider;
    }

    public void setMachineIdProvider(String machineIdProvider) {
        this.machineIdProvider = machineIdProvider;
    }

    public IdService getIdService(MachineIdProvider machineIdProvider){
        IdServiceImpl idServiceImpl = new IdServiceImpl();
        idServiceImpl.setMachineIdProvider(machineIdProvider);
        if (this.type != -1)
            idServiceImpl.setType(this.type);
        if (this.version != -1)
            idServiceImpl.setVersion(this.version);
        idServiceImpl.init();
        return idServiceImpl;
    }
}
